package utils;

import eg.Moneydemo;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据操作相关工具类
 */
public class DataBaseUtil {

    /**
     * 从文件读取
     */
    public static List<Moneydemo> read(String filepath) throws IOException {
        List<Moneydemo> lst = new ArrayList<>();
        FileInputStream file = new FileInputStream(filepath);
        ObjectInputStream reader = new ObjectInputStream(file);
        while (true) {
            try {
                Moneydemo Cls = (Moneydemo) reader.readObject();
                lst.add(Cls);
            } catch (EOFException e) {
                System.out.println("读取完成");
                break;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        file.close();
        reader.close();
        return lst;
    }

    /**
     * 写入文件
     */
    public static void write(String filepath,List<Moneydemo> moneydemos) throws IOException {
        FileOutputStream file = new FileOutputStream(filepath);
        ObjectOutputStream writer = new ObjectOutputStream(file);
        for (Moneydemo Cls : moneydemos) {
            writer.writeObject(Cls);
        }
        file.close();
        writer.close();
    }


    public static void main(String[] args) throws IOException {
        String filepath = "D://data.txt";
        List<Moneydemo> moneydemos = new ArrayList<>();
        Moneydemo m1 = new Moneydemo();
        m1.setName("test1");
        m1.setCreateDate(new Date());
        m1.setChangemoney("1");
        m1.setAllmoney("1");
        moneydemos.add(m1);

        Moneydemo m2 = new Moneydemo();
        m2.setName("test2");
        m2.setCreateDate(new Date());
        m2.setChangemoney("2");
        m2.setAllmoney("2");
        moneydemos.add(m2);

        write(filepath,moneydemos);

        List<Moneydemo> moneydemoList = read(filepath);
        for (Moneydemo moneydemo : moneydemoList) {
            System.out.println(moneydemo.getName());
        }
    }

}
